<template>
    消息列表<br>
   
    <ul>
        <li v-for="i in messagelist">
            {{ i.mes }}
        </li>
    </ul>
    <el-input v-model="mes" placeholder="请输入消息"></el-input>
    <el-button @click="send">发送</el-button>


</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router';

const socket = ref(null)
const router = useRouter();
const userid=1
const messagelist = ref([])
const mes = ref()

const send=()=>{
    const room = "user"+userid
    socket.value.send(JSON.stringify({
        "mes": mes.value,
        "to": room
    }),
    mes.value="",
    )
}

const initwesocket=()=>{
    const room = "user"+userid
    socket.value = new WebSocket("ws://localhost:8000/room/"+room+"/")
    //当客户端与服务端刚创建连接（self.accept）时触发
    socket.value.onopen=(event)=>{
        console.log("连接成功")
    }
    //回调函数，客户端接收服务端发消息
    socket.value.onmessage=(event)=>{
        const vdata = JSON.parse(event.data)
        messagelist.value.push(vdata)
    }
}

onMounted(()=>{
    initwesocket()
})

</script>





